package cn.weisoft.redisdemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

@SpringBootApplication
public class RedisDemoApplication {

    @Autowired
    private RedisTemplate redisTemplate=null;

    @Autowired
    private RedisConnectionFactory redisConnectionFactory = null;


    @Autowired
    @Qualifier("redisMessageListener")
    private MessageListener redisMessageListener = null;

    @Autowired
    @Qualifier("redisMessageListener2")
    private MessageListener redisMessageListener2 = null;

    private ThreadPoolTaskScheduler threadPoolTaskScheduler = null;


    @Bean
    public ThreadPoolTaskScheduler initTaskScheduler(){
        if(threadPoolTaskScheduler!=null){
            return threadPoolTaskScheduler;
        }
        threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.setPoolSize(20);
        return threadPoolTaskScheduler;
    }

    @Bean
    public RedisMessageListenerContainer initRedisContainer(){
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        container.setTaskExecutor(initTaskScheduler());
        Topic topic = new ChannelTopic("topic1");
        Topic topic2 = new ChannelTopic("topic2");
        container.addMessageListener(redisMessageListener,topic);
        container.addMessageListener(redisMessageListener2,topic);
        container.addMessageListener(redisMessageListener,topic2);
        return container;
    }

    public static void main(String[] args) {
        SpringApplication.run(RedisDemoApplication.class, args);

    }

}
